package com.caird.pmp.iot.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class BbFrameEncoder extends MessageToByteEncoder<ByteBuf> {

    @Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf in, ByteBuf out) throws Exception {
         escape(in, out);
    }

    /**
     * 转义
     * in：含7E头尾的完整报文
     */
    public void escape(ByteBuf in, ByteBuf out) {

        byte b;

        if (in.readableBytes() < 2)
            return ;

        out.writeByte(in.readByte());
        while (in.readableBytes() > 1) {
            b = in.readByte();
            switch (b) {
                case 0x7D:
                    out.writeByte(0x7d);
                    out.writeByte(0x01);
                    break;
                case 0x7E:
                    out.writeByte(0x7d);
                    out.writeByte(0x02);
                    break;
                default:
                    out.writeByte(b);
                    break;
            }
        }
        out.writeByte(in.readByte());
    }
}
